package com.yunduo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.config.shiro.ShiroConfig;
import com.yunduo.entity.User;
import com.yunduo.entity.vo.UserQuery;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.service.UserService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户控制类
 */
@RequiresRoles({"user"})
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private ShiroConfig shiroConfig;

    //获取用户基本信息
    @GetMapping("/user/info")
    public CommonReturn info(HttpServletRequest request){
        User token = JwtUtils.getDataByJwtToken(request);
        User user = userService.getUserByName(token.getName());
        Map<String,Object> data = new HashMap<>();
        data.put("roles", user.getRole());
        data.put("name", user.getName());
        data.put("avatar", user.getAvatar());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS,data);
    }

    //查询所有用户
    @GetMapping("/user")
    public CommonReturn getUserList(){
        List<User> list = userService.list(createLambdaUserQuery());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("userList",list);
    }

    //查询某个用户 不返回密码
    @GetMapping("/user/{id}")
    public CommonReturn getUser(@PathVariable("id") String id){
        LambdaQueryWrapper<User> userQuery = createLambdaUserQuery();
        userQuery.eq(User::getId,id);
        User user = userService.getOne(userQuery);
        if(null == user){
            return CommonReturn.ERROR(ResultCode.ERROR).setMessage("用户不存在");
        }
        user.setPassword("");
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("user",user);
    }

    //增加用户
    @PostMapping("/user")
    public CommonReturn addUser(@RequestBody User user){
        User onlyName = userService.getUserByName(user.getName());
        if(null != onlyName){
            return CommonReturn.ERROR(UserCode.USER_NAME_REPEAT);
        }
        String password = user.getPassword();
        user.setPassword(encryPassword(password));
        boolean save = userService.save(user);
        if(!save){
            throw new OperationException(ResultCode.UNDEFINE);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("add",true);
    }

    //修改用户
    @PutMapping("/user")
    public CommonReturn updateUser(@RequestBody User user){
        if (isNotEmpty(user.getPassword())) {
            String encrypt = encryPassword(user.getPassword());
            user.setPassword(encrypt);
        }
        boolean update = userService.updateById(user);
        if(!update){
            return CommonReturn.ERROR(ResultCode.UNDEFINE);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("update",true);
    }

    //软删除用户
    @DeleteMapping("/user/{deletId}")
    public CommonReturn deleteUser(@PathVariable("deletId") String id){
        boolean isDelete = userService.removeById(id);
        if(!isDelete){
            return CommonReturn.ERROR(ResultCode.UNDEFINE);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("delete",true);
    }

    //用户模糊查询
    @GetMapping("/user/selectUsersByName")
   public CommonReturn getUsersByName(String name) {
        List<User> list = userService.getUsersByName(name,5);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }

    //用户分页查询
    @PostMapping("/user/page")
    public CommonReturn getUserByPageQuery(@RequestBody UserQuery query){
        Page<User> page = new Page<>(query.getCurrentPage(),query.getPageItems());
        LambdaQueryWrapper<User> userQuery = createLambdaUserQuery();
        userQuery.likeRight(isNotEmpty(query.getName()),User::getName,query.getName());
        if(query.getCreateBegin() != null){
            LocalDateTime begin = splitDateString(query.getCreateBegin());
            userQuery.ge(User::getGmtCreate,begin);
        }
        if(query.getCreateEnd() != null){
            LocalDateTime end = splitDateString(query.getCreateEnd());
            userQuery.le(User::getGmtCreate,end);
        }
        userService.page(page,userQuery);
        HashMap<String,Object> data = new HashMap<>();
        data.put("list",page.getRecords());
        data.put("listSize",page.getRecords().size());
        data.put("total",page.getTotal());
        data.put("current",page.getCurrent());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS,data);
    }

    //批量删除用户
    @DeleteMapping("/user/delete")
    public CommonReturn adminDeleteUsers(@RequestBody String[] ids){
        boolean isDelete = userService.removeByIds(Arrays.asList(ids));
        if(!isDelete){
            return CommonReturn.ERROR(ResultCode.UNDEFINE);
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("delete",true);
    }

    //获取lambdaquery 用户状态为未删除
    private LambdaQueryWrapper<User> createLambdaUserQuery(){
        return new LambdaQueryWrapper<User>().eq(User::getIsDeleted,false);
    }

    //检查字符串是否为空
    private boolean isNotEmpty(String obj){
        return !StringUtils.isEmpty(obj);
    }

    //切割日期字符串 - 返回日期
    private LocalDateTime splitDateString(String date){
        try{
            String[] split = date.split("-");
            int year = Integer.valueOf(split[0]);
            int month = Integer.valueOf(split[1]);
            int day = Integer.valueOf(split[2]);
            return LocalDateTime.of(year,month,day,0,0);
        } catch (Exception e){
            throw new OperationException(ResultCode.ERROR.getCode(),"格式错误");
        }
    }

    //加密密码
    private String encryPassword(String password){
        SimpleHash simpleHash = new SimpleHash(shiroConfig.encryAlgorithm,password, shiroConfig.salt,shiroConfig.encryCount);
        return simpleHash.toString();
    }
}
